<template>
  <div class="home">
    <div class="survey-selector">
      <div class="header">
        <h1>医疗评估量表系统</h1>
        <p class="subtitle">专业的临床评估工具平台</p>
      </div>

      <div class="survey-options">
        <div class="survey-card" @click="navigateToSurvey('/fried')">
          <div class="card-icon">🏃‍♂️</div>
          <h3>Fried衰弱评估</h3>
          <p>基于体重减轻、疲劳感、握力、步行速度、体力活动等5个维度的衰弱评估</p>
          <div class="card-footer">
            <span class="assessment-time">评估时间：5-10分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/rockwood')">
          <div class="card-icon">⚕️</div>
          <h3>Rockwood临床衰弱量表</h3>
          <p>基于临床判断的9级衰弱评估量表，从非常健康到严重衰弱的全面评估</p>
          <div class="card-footer">
            <span class="assessment-time">评估时间：3-5分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/gpm')">
          <div class="card-icon">🩺</div>
          <h3>老年疼痛量表（GPM）</h3>
          <p>专门针对老年人疼痛评估的综合量表，涵盖疼痛程度、功能影响等多个维度</p>
          <div class="card-footer">
            <span class="assessment-time">评估时间：10-15分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/nrs')">
          <div class="card-icon">📊</div>
          <h3>NRS疼痛评估量表</h3>
          <p>数字评定量表，采用0-10分评分系统，快速准确评估疼痛程度和特征</p>
          <div class="card-footer">
            <span class="assessment-time">评估时间：5-8分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/psqi')">
          <div class="card-icon">🌙</div>
          <h3>匹兹堡睡眠质量指数(PSQI)</h3>
          <p>评估睡眠质量、入睡时间、睡眠效率和日间功能的综合量表</p>
          <div class="card-footer">
            <span class="assessment-time">评估时间：8-12分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/hamd')">
          <div class="card-icon">🧠</div>
          <h3>汉密尔顿抑郁量表(HAMD)</h3>
          <p>专业的抑郁症状评估量表，包含17个评估项目，全面评估抑郁程度和自杀风险</p>
          <div class="card-footer">
            <span class="assessment-time">评估时间：15-20分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/oral')">
          <div class="card-icon">🦷</div>
          <h3>口腔检查表</h3>
          <p>全面的口腔健康状况评估，包括牙齿状况、牙周情况、口腔黏膜和颌面外科检查</p>
          <div class="card-footer">
            <span class="assessment-time">检查时间：20-30分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/ohip14')">
          <div class="card-icon">😊</div>
          <h3>口腔健康影响程度量表(OHIP-14)</h3>
          <p>评估口腔健康问题对个体生活质量的影响程度，包含14个评估项目，采用Likert 5级评分</p>
          <div class="card-footer">
            <span class="assessment-time">评估时间：10-15分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/personal-info')">
          <div class="card-icon">📋</div>
          <h3>个人信息登记表</h3>
          <p>用于医疗评估和健康管理的个人信息收集，包括基本信息、社会信息、健康信息和紧急联系人等</p>
          <div class="card-footer">
            <span class="assessment-time">登记时间：5-10分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/cognitive')">
          <div class="card-icon">🧠</div>
          <h3>认知能力记录表</h3>
          <p>评估个体的认知功能状态，包括记忆力、注意力、执行功能、语言功能、视空间功能和计算能力等多个维度</p>
          <div class="card-footer">
            <span class="assessment-time">评估时间：15-20分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/personality')">
          <div class="card-icon">👤</div>
          <h3>性格特征记录表</h3>
          <p>中国社区长者工效学能力特征测量，评估个人性格特征及过去一周的精神状态，包括焦虑和抑郁评估</p>
          <div class="card-footer">
            <span class="assessment-time">评估时间：10-15分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/outdoor-activity')">
          <div class="card-icon">🚶</div>
          <h3>个体行为记录表（户外活动路线）</h3>
          <p>记录最近1-2周的社区步行活动内容，包括活动类型、时间、场所、使用物品和路线等信息，最多可记录6条活动</p>
          <div class="card-footer">
            <span class="assessment-time">记录时间：5-10分钟</span>
          </div>
        </div>

        <div class="survey-card" @click="navigateToSurvey('/leisure-activity')">
          <div class="card-icon">🎯</div>
          <h3>空闲活动频率量表</h3>
          <p>评估个体在空闲时间参与各种活动的频率，包括做家务、运动、娱乐、社交等14项活动，以及健身器材使用情况</p>
          <div class="card-footer">
            <span class="assessment-time">评估时间：5-10分钟</span>
          </div>
        </div>
      </div>

      <div class="footer-note">
        <p>请选择适合的评估量表开始专业评估</p>
      </div>

      <div class="export-section">
        <button class="export-btn" @click="showExportDialog">📥 批量导出数据</button>
      </div>
    </div>

    <!-- 导出对话框 -->
    <div v-if="showExport" class="export-dialog-overlay" @click="closeExportDialog">
      <div class="export-dialog" @click.stop>
        <div class="export-dialog-header">
          <h2>批量导出数据</h2>
          <button class="close-btn" @click="closeExportDialog">×</button>
        </div>
        <div class="export-dialog-body">
          <div v-if="loadingIds" class="loading">正在加载编号列表...</div>
          <div v-else-if="surveyIds.length === 0" class="no-data">暂无可用编号</div>
          <div v-else>
            <div class="select-all-section">
              <label class="checkbox-label">
                <input type="checkbox" :checked="allSelected" @change="toggleSelectAll" />
                <span>全选</span>
              </label>
            </div>
            <div class="survey-ids-list">
              <label v-for="id in surveyIds" :key="id" class="checkbox-label">
                <input type="checkbox" :value="id" v-model="selectedIds" />
                <span>{{ id }}</span>
              </label>
            </div>
            <div class="password-input">
              <label>导出密码：</label>
              <input type="password" v-model="exportPassword" placeholder="请输入导出密码" />
            </div>
          </div>
        </div>
        <div class="export-dialog-footer">
          <button class="cancel-btn" @click="closeExportDialog">取消</button>
          <button class="confirm-btn" @click="handleBatchExport" :disabled="selectedIds.length === 0 || isExporting">
            {{ isExporting ? '导出中...' : '确认导出' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HomePage',
  data() {
    return {
      showExport: false,
      surveyIds: [],
      selectedIds: [],
      exportPassword: '',
      loadingIds: false,
      isExporting: false
    }
  },
  computed: {
    allSelected() {
      return this.surveyIds.length > 0 && this.selectedIds.length === this.surveyIds.length
    }
  },
  methods: {
    navigateToSurvey(path) {
      this.$router.push(path)
    },
    async showExportDialog() {
      this.showExport = true
      this.loadingIds = true
      this.selectedIds = []
      this.exportPassword = ''

      try {
        const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/get-survey-ids`)
        const data = await response.json()
        if (data.success) {
          this.surveyIds = data.surveyIds || []
        } else {
          alert('获取编号列表失败')
        }
      } catch (error) {
        console.error('获取编号列表失败:', error)
        alert('获取编号列表失败，请检查服务器连接')
      } finally {
        this.loadingIds = false
      }
    },
    closeExportDialog() {
      this.showExport = false
      this.selectedIds = []
      this.exportPassword = ''
      this.isExporting = false
    },
    toggleSelectAll() {
      if (this.allSelected) {
        this.selectedIds = []
      } else {
        this.selectedIds = [...this.surveyIds]
      }
    },
    async handleBatchExport() {
      if (this.selectedIds.length === 0) {
        alert('请至少选择一个编号')
        return
      }

      if (!this.exportPassword) {
        alert('请输入导出密码')
        return
      }

      this.isExporting = true

      try {
        const response = await fetch(`${window.location.protocol}//${window.location.hostname}:13000/api/batch-export`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            surveyIds: this.selectedIds,
            password: this.exportPassword,
            exportOptions: {
              includeRawData: true,
              includeStatistics: true
            }
          })
        })

        if (response.status === 401) {
          alert('密码错误，请重新输入！')
          return
        }

        if (!response.ok) {
          const errorData = await response.json().catch(() => ({ detail: '导出失败' }))
          alert(errorData.detail || '导出失败')
          return
        }

        // 获取服务器返回的压缩包
        const blob = await response.blob()

        if (blob.size === 0) {
          alert('所选编号下没有数据！')
          return
        }

        // 下载服务器生成的压缩包
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-')
        link.download = `批量导出数据_${timestamp}.zip`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        alert('数据导出成功！')
        this.closeExportDialog()
      } catch (error) {
        console.error('导出失败:', error)
        alert('导出失败，请检查网络连接')
      } finally {
        this.isExporting = false
      }
    }
  }
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.survey-selector {
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  max-width: 1200px;
  width: 100%;
}

.header {
  text-align: center;
  margin-bottom: 40px;
}

.header h1 {
  font-size: 2.5em;
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-weight: 700;
}

.subtitle {
  font-size: 1.2em;
  color: #7f8c8d;
  margin: 0;
}

.survey-options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.survey-card {
  background: #f8f9fa;
  border: 2px solid #e9ecef;
  border-radius: 15px;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.survey-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
  border-color: #007bff;
}

.card-icon {
  font-size: 3em;
  margin-bottom: 20px;
}

.survey-card h3 {
  font-size: 1.5em;
  color: #2c3e50;
  margin: 0 0 15px 0;
  font-weight: 600;
}

.survey-card p {
  color: #6c757d;
  line-height: 1.6;
  margin: 0 0 20px 0;
  font-size: 0.95em;
}

.card-footer {
  border-top: 1px solid #e9ecef;
  padding-top: 15px;
  margin-top: 20px;
}

.assessment-time {
  color: #28a745;
  font-weight: 500;
  font-size: 0.9em;
}

.footer-note {
  text-align: center;
  margin-top: 30px;
}

.footer-note p {
  color: #6c757d;
  font-style: italic;
  margin: 0;
}

.export-section {
  text-align: center;
  margin-top: 30px;
}

.export-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 15px 30px;
  font-size: 1.1em;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.export-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.export-btn:active {
  transform: translateY(0);
}

/* 导出对话框样式 */
.export-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.export-dialog {
  background: white;
  border-radius: 15px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.export-dialog-header {
  padding: 20px 25px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.export-dialog-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.5em;
}

.close-btn {
  background: none;
  border: none;
  font-size: 2em;
  color: #6c757d;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  line-height: 30px;
  transition: color 0.3s ease;
}

.close-btn:hover {
  color: #2c3e50;
}

.export-dialog-body {
  padding: 20px 25px;
  overflow-y: auto;
  flex: 1;
}

.loading,
.no-data {
  text-align: center;
  color: #6c757d;
  padding: 40px 0;
}

.select-all-section {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px;
  border-radius: 5px;
  transition: background-color 0.2s ease;
  margin-bottom: 5px;
}

.checkbox-label:hover {
  background-color: #f8f9fa;
}

.checkbox-label input[type="checkbox"] {
  margin-right: 10px;
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.checkbox-label span {
  color: #2c3e50;
  font-size: 1em;
}

.survey-ids-list {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 20px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 10px;
}

.password-input {
  margin-top: 20px;
}

.password-input label {
  display: block;
  margin-bottom: 8px;
  color: #2c3e50;
  font-weight: 500;
}

.password-input input {
  width: 100%;
  padding: 10px;
  border: 1px solid #e9ecef;
  border-radius: 5px;
  font-size: 1em;
  box-sizing: border-box;
}

.password-input input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.export-dialog-footer {
  padding: 20px 25px;
  border-top: 1px solid #e9ecef;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn,
.confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  font-size: 1em;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: #f8f9fa;
  color: #6c757d;
}

.cancel-btn:hover {
  background: #e9ecef;
}

.confirm-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.confirm-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(102, 126, 234, 0.4);
}

.confirm-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .survey-selector {
    padding: 20px;
  }

  .header h1 {
    font-size: 2em;
  }

  .survey-options {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .survey-card {
    padding: 20px;
  }

  .export-dialog {
    width: 95%;
    max-height: 90vh;
  }

  .export-dialog-header h2 {
    font-size: 1.2em;
  }
}
</style>